// pages/hotspot/details/details.js
const util = require('../../../utils/util');
const app = getApp();
import {
  articleFind,
  articleReviewList,
  articleReviewSave
} from '../../../api/article';
import {
  talentFollowSave
} from '../../../api/member';
import {
  findAffiliated
} from '../../../api/shop';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentIndex: 0,
    APP_OSSURL_API: app.APP_OSSURL_API,
    attentionDisable: false,
    shareDisable: false,
    showMore: false,
    showMoreContent: false,
    focusOnPanel: false,
    panelBottom: 0,
    comment: ""
  },

  bindChange(e) {
    this.setData({
      currentIndex: e.detail.current
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      articleId: options.id
    })
    // debugger
    /*从分享链接打开先进入首页再跳转到分享的页面 TODO 未测试*/
    if (options.url) {
      let url = decodeURIComponent(options.url);
      wx.navigateTo({
        url
      })
    } else { //  if(options.id)
      this.getArticle(options.id)
      this.getarticleReviewList(options.id)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if(this.data.shareThumbnail){
      return {
        imageUrl:this.data.shareThumbnail
      }
    }
  },
  ifAuth: function () {
    if (!app.globalData.token) {
      wx.showToast({
        icon: 'none',
        title: '请先登录！',
      })
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/index',
        })
      }, 500)
      return false
    }
    return true
  },
  cancelBehavior: function () {
    this.setData({
      showReplay: false
    })
  },


  getArticle: function (id) {
    articleFind(id).then(res => {
      let _talent = res.data.talent
      let _article = res.data.article
      _article.publishDate = util.datetime(_article.createDate, '.')
      let _images = _article.articleMeta.images
      let _thumbnail = null
      if(_article.articleMeta.images.length){
      _thumbnail = util.thumbnail(_article.articleMeta.images[0], 500, 400)
    }
      _article.articleMeta.images = _images.map(e => {
        return util.thumbnail(e, 375, 500)
      })
      this.setData({
        shareThumbnail:_thumbnail,
        showMore: _article.content.match(/.{70}|(.*\n.*){3}/g) ? true : false,
        talent: _talent,
        article: _article,
        attention: _talent && _talent.followFlag
      })
      _article.productId && this.getAffiliated(_article.productId)
    })
  },

  getAffiliated: function (productId) {
    findAffiliated(productId).then(res => {
      let _affiliated = res.data.shop
      _affiliated.distance = util.rateConverter(_affiliated.distance)
      _affiliated.score = _affiliated.score.toFixed(1)
      _affiliated.logo = util.thumbnail(_affiliated.logo, 80, 59)
      this.setData({
        affiliated: _affiliated
      })
    })
  },

  /**
   * 创建/修改节点及其子节点的属性 
   * @param {Array} node 节点
   */
  recursion: function (node) {
    console.log(node)
    return node.map(res => {
      res.commentDate = util.datetimeFormat(res.createDate, '.')
      if (res.child)
        res.child = this.recursion(res.child)
      return res
    })
  },

  getarticleReviewList: function (id) {
    articleReviewList({
      articleId: id
    }).then(res => {
      // let _articleReview = res.data.data
      let _articleReview = []
      this.setData({
        articleReview: _articleReview,
        articleReviewSize: res.data.size,
      })
      setTimeout(() => {
        this.setData({
          articleReview: this.recursion(_articleReview)
        })
      }, 10)

    })
  },

  /**
   * 防抖函数 TODO 待完善，500ms内不能重复点击
   * @param {String} enable 使能变量
   * @param {Boolean} changeTo 初始值
   */
  debounce: function (enable, changeTo) {
    this.setData({
      [enable]: changeTo
    })
    let enableTimeout = setTimeout(() => {
      this.setData({
        [enable]: !changeTo
      })
      clearTimeout(enableTimeout)
    }, 700)
  },

  /**
   * 进入达人/个人主页
   */
  toPersonalHomePage: function () {
    if (!(this.data.talent && this.data.talent.id)) {
      wx.showToast({
        title: '无法进入达人主页',
      })
      return
    }
    wx.navigateTo({
      url: '/pages/member/follow/dynamic/index?id=' + this.data.talent.id
    })
  },

  /**
   * 切换关注/不关注
   */
  switchAttention: function () {
    // debugger
    if (!this.ifAuth()) {
      return
    }
    if (this.data.attentionDisable) {
      return
    }
    let _attention = this.data.attention

    this.debounce("attentionDisable", !this.data.attentionDisable)
    if (!this.data.talent) {
      wx.showToast({
        icon: 'none',
        title: '关注失败'
      })
      return
    }
    talentFollowSave({
      follow: !_attention,
      talentId: this.data.talent.id
    }).then(res => {
      wx.showToast({
        title: '关注成功'
      })
      this.setData({
        attention: _attention
      })
      this.getArticle(this.data.articleId)
    })

  },


  /**
   * 分享
   */
  share: function () {
    // if (!this.ifAuth()) {
    //   return
    // }
    this.debounce("shareDisable", true)
  },

  /**
   * 查看全部
   */
  showMoreContent: function (e) {
    this.setData({
      showMoreContent: !this.data.showMoreContent
    })
  },

  /**
   * 附近店铺/店铺详情
   */
  toShopDetail: function () {
    wx.navigateTo({
      url: `/pages/shop/shopDetail/index?shopId=${this.data.shopId}`,
    })
  },
  /**
   * 附近景点/景点详情
   */
  toRelativeShop: function (e) {
    wx.navigateTo({
      url: `/pages/shop/shopDetail/index?shopId=${e.currentTarget.dataset.id}`,
    })
  },
  showPanel: function () {
    this.setData({
      focusOnPanel: true,
      comment: ""
    })
  },
  adjustPanel: function (e) {
    this.setData({
      panelBottom: e.detail.height || 0
    })
  },
  toCommentView: function (e) {
    this.setData({
      toView: "comment"
    })
  },
  replay: function (e) {
    if (!this.ifAuth()) {
      return
    }
    this.showPanel()
    this.setData({
      comment: "回复 " + e.detail.nickname + ' : ',
      commentHeader: "回复 " + e.detail.nickname + ' : ',
      forReviewId: e.detail.forReviewId,
      parentId: e.detail.parentId,
    })
  },
  favourIt: function () {
    if (!this.ifAuth()) {
      return
    }

    if (this.data.article.laud) {
      wx.showToast({
        icon: 'none',
        title: '您已点过赞！',
      })
      return
    }
    util.articleLaud(this.data.article.id, this).then(res => {
      this.getArticle(this.data.articleId)
    })
  },
  reviewSave: function (e) {
    if (!this.ifAuth()) {
      return
    }
    if (!this.data.comment) {
      wx.showToast({
        icon: 'none',
        title: '请发表您的评论！',
      })
      return
    }
    let withId = this.data.comment.indexOf(this.data.commentHeader) == 0
    articleReviewSave({
      articleId: this.data.article.id,
      content: this.data.comment,
      forReviewId: withId ? this.data.forReviewId : NaN,
      parentId: withId ? this.data.parentId : NaN,
    }).then(res => {
      wx.showToast({
        icon: 'success',
        title: '已提交，待审核！',
      })

      // debugger
      // this.getarticleReviewList(this.data.articleId)
    })
  },
  onShareTimeline(){
    
  },
   /**
   * 预览图片/视频
   */
  previewMedia: function (e) {
    let _uploadFiles = this.data.article.articleMeta.images
    wx.previewMedia({
      sources: _uploadFiles.map(e => {
        return {
          url: e,
          type: "image"
        }
      }),
      current: this.data.currentIndex
    })
  },

})